/**
 *
 */
package cardval.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;

import cardval.dao.CardInfoDao;
import cardval.dao.CardTransLogDao;
import cardval.dao.PartnerDao;
import cardval.entity.CardInfo;
import cardval.entity.PartnerInfo;
import cardval.entity.PartnerOverview;
import cardval.entity.PartnerTotalOverview;
import cardval.entity.PartnerTrans;
import cardval.entity.Result;
import cardval.util.DateUtil;
import cardval.util.StringUtil;

/**
 * @author Renne66
 * @Description: 系统控制器
 * @email 465119455@qq.com
 * @date 2016年4月21日
 */
@Controller
public class SystemController {
    private static final Logger logger = Logger.getLogger(SystemController.class);
    @Autowired
    private SystemService systemService;

    @Resource
    private PartnerDao partnerDao;

    @Resource
    private CardInfoDao cardInfoDao;
    
    @Resource
    private CardTransLogDao cardTransLogDao;

    /**
     *
     * 银行卡账户验证
     *
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/validationCard")
    public void validationCard(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	//第一个时间点进入验证平台
		Date st1Date = new Date();
        //初始化返回值
        Result result = null;
        //获取接口参数
        String partnerNo = request.getParameter("PARTNERNO");
        String cardNo = request.getParameter("CARDNO");
        String sign = request.getParameter("SIGN");
        String cardName = request.getParameter("CARDNAME");
        String cardMobile = request.getParameter("CARDMOBILE");
        String cardIdtype = request.getParameter("CARDIDTYPE");
        String cardIdcard = request.getParameter("CARDIDCARD");
        String serialNo = request.getParameter("SERIALNO");
        String pkey = request.getParameter("PKEY");
        List<PartnerInfo> partnerInfos = partnerDao.queryPartners(partnerNo);

        String localKey = null;
        if (!CollectionUtils.isEmpty(partnerInfos) && partnerInfos.size() != 0) {
            PartnerInfo partnerInfo = partnerInfos.get(0);
            if (partnerInfo != null) {
                localKey = partnerInfo.getPARTNER_KEY();
            }
        }
        
        String txt = pkey + "|" + partnerNo + "|" + serialNo + "|" + cardNo + "|" + cardMobile + "|" + cardIdcard + "|" + cardName + "|" + cardIdtype;
        //账号必须存在 新增serialNo必须存在
        if (StringUtil.isEmpty(cardNo, partnerNo, sign, pkey, serialNo) ||
                (StringUtil.isEmpty(cardName)) && (StringUtil.isEmpty(cardMobile)) && (StringUtil.isEmpty(cardIdcard))) {
            result = new Result("10", "参数错误");
        } else if (!StringUtils.equals(localKey, pkey)) {
            result = new Result("10", "密钥不匹配");
        } else if (!sign.equals(DigestUtils.md5Hex(txt))) {
            result = new Result("10", "sign错误");
        } else if (!StringUtil.isEmpty(cardIdtype) && !cardIdtype.equals("01")) {
            result = new Result("10", "不支持证件类型");                  
        } else if (serialNo.length() > 40) {
        	result = new Result("10", "流水号有误长度超过40");      	
        } else if (cardNo.length() > 20) {
        	result = new Result("10", "卡号有误长度超过20");
        } else if (!StringUtil.isEmpty(cardName) && cardName.length() > 15) {
        	result = new Result("10","姓名有误长度超过15");
        }else if (!StringUtil.isEmpty(cardMobile) && cardMobile.length() > 11) {
        	result = new Result("10","手机号有误长度超过11");
        }else {
            //初始化参数Map并验证参数
            CardInfo paramsCard = new CardInfo(cardNo);
            //新增流水号和商户
            	paramsCard.setSERIALNO_(serialNo);
            	paramsCard.setPARTNERNO_(partnerNo);
            //账户名和手机号选填
            if (!StringUtil.isEmpty(cardName)) paramsCard.setCARD_NAME_(cardName);
            if (!StringUtil.isEmpty(cardMobile))
                paramsCard.setCARD_MOBILE_(cardMobile);
            //证件类型和证件号码必须同时存在或不存在
            if (!StringUtil.isEmpty(cardIdtype, cardIdcard)) {
            	//身份证的验证           	
                paramsCard.setCARD_IDTYPE_(cardIdtype);
                paramsCard.setCARD_IDCARD_(cardIdcard);                  
            } 
            
            result = systemService.validation(st1Date,paramsCard, partnerNo);   
            
        }
        
        logger.info("validationcard:" + JSONArray.toJSON(result).toString());
        response.setCharacterEncoding("UTF-8"); //设置编码格式
        response.setContentType("text/html");   //设置数据格式
        PrintWriter out = response.getWriter(); //获取写入对象
        out.print(JSONArray.toJSON(result).toString()); //将json数据写入流中
        out.flush();
        //返回总的交易时间
       /* CardInfoTransLog cTransLog = result.getCardInfoTransLog();
        Date st4Date = new Date();
        String time4 = DateUtil.format(st4Date, DateUtil.YYYY_MM_DD_HH_MM_SS_MS);
        long tolTime = (st4Date.getTime() - st1Date.getTime());// 得到两者的毫秒数
        cTransLog.setTIME4(time4);
        cTransLog.setTOLTIME(tolTime);
        cardTransLogDao.addCardTransLog(cTransLog);*/
        
    }

    /**
     * 根据卡号获取验证信息
     *
     * @param @param  request
     * @param @param  response
     * @param @throws IOException
     * @throws
     */
    @ResponseBody
    @RequestMapping(value = "/getCardInfos.do", method = RequestMethod.GET)
    public String getCardInfos(HttpServletRequest request, HttpServletResponse response) throws IOException {

        int offset = 0;

        int limit = 10;
        if (StringUtils.isNotBlank(request.getParameter("offset"))) {
            offset = Integer.parseInt(request.getParameter("offset"));
        }


        if (StringUtils.isNotBlank(request.getParameter("limit"))) {
            limit = Integer.parseInt(request.getParameter("limit"));
        }
        
       


        JSONObject jsonObject = new JSONObject();
        //获取流水号
        String serialNo = request.getParameter("serialNo");
        //获取商户号
        String partnerNo = request.getParameter("partnerNo");
        //获取卡号
        String cardNo = request.getParameter("cardNo");

        //获取姓名
        String cardName = request.getParameter("cardName");
        //获取手机号进行查询
        String cardMobile = request.getParameter("cardMobile");
        //新增身份证号查询
        String cardIdcard = request.getParameter("cardIdcard");

        /*if (cardNo != null && !cardNo.trim().equals("")) {
            List<CardInfo> cardInfos = systemService.getCardInfos(cardNo, offset, limit);
            jsonObject.put("rows", cardInfos);
            jsonObject.put("total", cardInfoDao.getCountCard(cardNo));
        }*/
        //添加用户的查看交易信息的权限 0922
        HttpSession session = request.getSession(false);
        if (session != null) {
            if (StringUtils.equals((String) session.getAttribute("isPartner"), "1")) {
                partnerNo = (String) session.getAttribute("current_user");
            }
        }
        List<CardInfo> cardInfos = systemService.getCardInfos(serialNo,partnerNo,cardNo,cardName,cardMobile,cardIdcard,limit,offset);
        jsonObject.put("rows", cardInfos);
        jsonObject.put("total", cardInfoDao.getCountCard(serialNo,partnerNo,cardNo,cardName,cardMobile,cardIdcard));
        return jsonObject.toJSONString();
    }

    @RequestMapping(value = "/delCardInfos.do", method = RequestMethod.POST)
    public void delCardInfos(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String cardId = request.getParameter("cardId");
        if (cardId != null && !cardId.trim().equals("")) {
            response.setContentType("text/html;charset=UTF-8");   //设置数据格式
            PrintWriter out = response.getWriter(); //获取写入对象
            out.print(systemService.delCardInfos(cardId)); //将数据写入流中
            out.flush();
        }
    }

    /**
     * 获取所有合作商
     *
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/getPartnerInfos.do", method = RequestMethod.GET)
    public String getPartnerInfos(HttpServletRequest request) throws IOException {

        int offset = 0;

        int limit = 10;
        if (StringUtils.isNotBlank(request.getParameter("offset"))) {
            offset = Integer.parseInt(request.getParameter("offset"));
        }

        if (StringUtils.isNotBlank(request.getParameter("limit"))) {
            limit = Integer.parseInt(request.getParameter("limit"));
        }
         
        //将商户信息开放,如果不是admin就仅仅显示本商户
        String partnerNo = request.getParameter("partnerNo");
        HttpSession session = request.getSession(false);
        if (session != null) {
            if (StringUtils.equals((String) session.getAttribute("isPartner"), "1")) {
                partnerNo = (String) session.getAttribute("current_user");
            }
        }
        List<PartnerInfo> partnerInfos = systemService.getPartnerInfo(partnerNo, offset, limit);

        // 可通过bootstrap的自定义列来实现充值按钮
        if (session != null) {
            if (StringUtils.equals((String) session.getAttribute("isPartner"), "0")) {
                
                for (PartnerInfo p : partnerInfos) {
                	p.setOperate("<a onclick=\"editInfo(this)\" id=\"" + p.getPARTNER_NO_() + "\"style=\"cursor: hand\" data-toggle=\"modal\" data-target=\"#myModal\">\n" +
                			"                        充值\n" +
                			"                    </a>");
                }
            }
           /* //修改密码
			if (StringUtils.equals((String) session.getAttribute("isPartner"), "1")) {
			                
			                for (PartnerInfo p : partnerInfos) {
			                	p.setOperate("<a onclick=\"editInfo(this)\" id=\"" + p.getPARTNER_NO_() + "\"style=\"cursor: hand\" data-toggle=\"modal\" data-target=\"#myModal\">\n" +
			                			"                        修改密码\n" +
			                			"                    </a>");
			 }
		  }*/
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", partnerDao.queryPtrCount(partnerNo));
        jsonObject.put("rows", partnerInfos);
        return jsonObject.toJSONString();
    }


    /**
     * 获取合作商交易记录
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getPartnerTrans.do", method = RequestMethod.GET)
    public String getPartnerTrans(HttpServletRequest request, Integer limit, Integer offset, ModelMap map) throws JsonProcessingException {
        String transType = request.getParameter("TRANS_TYPE_");

        if (limit == null || limit == 0) {
            limit = 10;
        }
        
        //这里做了修改的话就可以显示全部的记录的0904
        if (offset == null || offset == 0) {
            offset = 0;
        }

        String partnerNo = request.getParameter("partnerNo");
        HttpSession session = request.getSession(false);
        if (session != null) {
            if (StringUtils.equals((String) session.getAttribute("isPartner"), "1")) {
                partnerNo = (String) session.getAttribute("current_user");
            }
        }

        List<PartnerTrans> partnerTrans = systemService.getPartnerTrans(partnerNo, transType, limit, offset);
        for (PartnerTrans x : partnerTrans) {
            x.setFmt(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(x.getTRANS_DATE_()));
            if (x.getTRANS_TYPE_() == 1) {
                x.setsType("充值");
            }
            if (x.getTRANS_TYPE_() == 2) {
                x.setsType("消费");
//                这里做了更改 以前是有个*的，每次消费-50
                x.setTRANS_MONEY_(x.getTRANS_MONEY_() * -1);
            }
        }
        map.put("total", partnerDao.queryPtrTransCount(partnerNo, transType));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", partnerDao.queryPtrTransCount(partnerNo, transType));
        jsonObject.put("rows", partnerTrans);

        return jsonObject.toJSONString();
    }

    /**
     * 添加合作商
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/addPartnerInfo.do", method = RequestMethod.POST)
    public String addPartnerInfo(HttpServletRequest request, RedirectAttributesModelMap redirectAttributesModelMap) throws IOException {
        Result result;
        String partnerNo = request.getParameter("PARTNER_NO_");
        String partnerName = request.getParameter("PARTNER_NAME_");
        String partnerMoney = request.getParameter("PARTNER_MONEY_");
        String contact = request.getParameter("contact");
        String mobile = request.getParameter("mobile");
        if (StringUtil.isEmpty(partnerNo, partnerName)) {
            result = new Result("10", "参数不能为空");
        } else {
            PartnerInfo partnerInfo = new PartnerInfo(partnerNo, partnerName, 0);
            partnerInfo.setContact(contact);
            partnerInfo.setMobiel(mobile);
            partnerInfo.setPARTNER_KEY(UUID.randomUUID().toString().replaceAll("-", ""));
            int id = systemService.addPartnerInfo(partnerInfo);
            partnerInfo.setID_(id);
            if (StringUtil.isNotEmpty(partnerMoney) && Integer.valueOf(partnerMoney) > 0) {
                systemService.transPartnerMoney(partnerInfo, Integer.valueOf(partnerMoney), 1);
            }
            result = new Result("0", "添加成功");
        }
        logger.info("addPartnerInfo:" + JSONArray.toJSON(result).toString());
        redirectAttributesModelMap.addAttribute("msger", "<b>添加成功</b>");
        return "redirect:/main.htm";
    }

    /**
     * 合作商充值
     *
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/addPartnerMoney.do", method = RequestMethod.POST)
    public void addPartnerMoney(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Result result;
        String partnerNo = request.getParameter("PARTNER_NO_");
        String transMoney = request.getParameter("TRANS_MONEY_");
        if (StringUtil.isEmpty(partnerNo, transMoney)) {
            result = new Result("10", "参数不能为空");
        } else {
            List<PartnerInfo> partnerInfos = systemService.getPartnerInfo(partnerNo);
            if (partnerInfos.size() == 0) {
                result = new Result("12", "合作商不存在");
            } else {
                PartnerInfo partnerInfo = partnerInfos.get(0);
                systemService.transPartnerMoney(partnerInfo, Integer.valueOf(transMoney), 1);
                result = new Result("00", "充值成功");
            }
        }
        logger.info("addPartnerMoney:" + JSONArray.toJSON(result).toString());
        response.setCharacterEncoding("UTF-8"); //设置编码格式
        response.setContentType("text/html");   //设置数据格式
        PrintWriter out = response.getWriter(); //获取写入对象
        out.print(JSONArray.toJSON(result).toString()); //将json数据写入流中
        out.flush();
    }
    
    /**
     * 合作商修改密码
     * @param request
     * @return
     */
    


    @ResponseBody
    @RequestMapping(value = "ptrOverView.do")
    public String getPtrOverView(HttpServletRequest request) {

        int offset = 0;

        int limit = 10;
        if (StringUtils.isNotBlank(request.getParameter("offset"))) {
            offset = Integer.parseInt(request.getParameter("offset"));
        }

        if (StringUtils.isNotBlank(request.getParameter("limit"))) {
            limit = Integer.parseInt(request.getParameter("limit"));
        }

        String partnerNo = request.getParameter("partnerNo");
        
        //新增根据日期进行查询操作0911 ----设置默认显示时间为最近两天 0921
        Date dNow = new Date();   //当前时间
        Date dBefore = new Date();

        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(dNow);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -1);  //设置为前一天
        dBefore = calendar.getTime();   //得到前一天的时间
        
        String dateStart = DateUtil.format(dBefore, DateUtil.YYYYMMDD);    //格式化前一天
        String dateEnd = DateUtil.format(dNow, DateUtil.YYYYMMDD); //格式化当前时间
       
        //设置值默认为当前的这两天
        if(StringUtils.isNotBlank(request.getParameter("dateStart"))) {
         dateStart = request.getParameter("dateStart");
        }
        if(StringUtils.isNotBlank(request.getParameter("dateEnd"))) {
        	 dateEnd = request.getParameter("dateEnd");
        }
        
        
        HttpSession session = request.getSession(false);
        if (session != null) {
            if (StringUtils.equals((String) session.getAttribute("isPartner"), "1")) {
                partnerNo = (String) session.getAttribute("current_user");
            }
        }
        List<PartnerOverview> partnerOverviews = partnerDao.queryPtrOverview(dateStart,dateEnd,partnerNo, offset, limit);

        for (PartnerOverview x : partnerOverviews) {
            if (x.getType() == 1) {
                x.setStype("充值");
            }
            if (x.getType() == 2) {
                x.setStype("消费");
                x.setSumAmt(x.getSumAmt() * -1);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", partnerDao.getPtrOVCount(dateStart,dateEnd,partnerNo));
        jsonObject.put("rows", partnerOverviews);

        return jsonObject.toJSONString();
    }
    
    
    //商户交易量总统计
    @ResponseBody
    @RequestMapping(value = "ptrTotalOverView.do" , method = RequestMethod.GET)
    public String getPtrTotalOverView(HttpServletRequest request) {

        int offset = 0;

        int limit = 10;
        if (StringUtils.isNotBlank(request.getParameter("offset"))) {
            offset = Integer.parseInt(request.getParameter("offset"));
        }

        if (StringUtils.isNotBlank(request.getParameter("limit"))) {
            limit = Integer.parseInt(request.getParameter("limit"));
        }

        String partnerNo = request.getParameter("partnerNo");
        //新增根据日期进行查询操作0911 默认是显示当月的交易信息0921
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.set(Calendar.DATE, 1);  
        Date dNow = new Date();   //当前时间
        Date mBegin = calendar.getTime();//获取当月第一天月初时间
         
       
        String dateStart = DateUtil.format(mBegin, DateUtil.YYYYMMDD);    //格式化前一天
        String dateEnd = DateUtil.format(dNow, DateUtil.YYYYMMDD); //格式化当前时间
       
        //设置值默认为当前的这两天
        if(StringUtils.isNotBlank(request.getParameter("dateStart"))) {
         dateStart = request.getParameter("dateStart");
        }
        if(StringUtils.isNotBlank(request.getParameter("dateEnd"))) {
        	 dateEnd = request.getParameter("dateEnd");
        }
        
        HttpSession session = request.getSession(false);
        if (session != null) {
            if (StringUtils.equals((String) session.getAttribute("isPartner"), "1")) {
                partnerNo = (String) session.getAttribute("current_user");
            }
        }
        List<PartnerTotalOverview> partnerOverviews = partnerDao.queryPtrTotalOverview(dateStart,dateEnd,partnerNo, offset, limit);

        for (PartnerTotalOverview x : partnerOverviews) {
            if (x.getType() == 1) {
                x.setStype("充值");
            }
            if (x.getType() == 2) {
                x.setStype("消费");
                x.setSumAmt(x.getSumAmt() * -1);
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", partnerDao.getPtrTotalOVCount(dateStart,dateEnd,partnerNo));
        jsonObject.put("rows", partnerOverviews);

        return jsonObject.toJSONString();
    }
    
    
}